package com.ssau.expert.gui.master;

import com.ssau.expert.common.CallableTask;
import com.ssau.expert.entity.Ship;
import com.ssau.expert.gui.app.Locator;
import com.ssau.expert.gui.common.Controller;
import com.ssau.expert.gui.common.MyControls;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

/**
 * Author: Sergey Saiyan
 * Created: 05.09.13 11:51
 */
public class ExpertFrame extends JFrame implements ExpertPresenter {

    private static final long serialVersionUID = -3985338753569078946L;

    private static final String NAME = "Экспертная система. Режим эксперта";
    private JButton editShipButton;
    private JTable shipTable;

    @Override
    public void init() {
        this.setLayout(null);
        initComponents();
        initDisposition();

        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Controller.get().showLoginFrame();
            }
        });
    }

    @Override
    public void showFrame() {
        setName(NAME);
        setTitle(NAME);
        setVisible(true);
    }

    @Override
    public void displayUserInput(String shipProfileAnswer, String staffAnswer, String distanceAnswer) {
        profileJTextField.setText(shipProfileAnswer);
        autonomyJTextField.setText(distanceAnswer);
        personalJTextField.setText(staffAnswer);
    }

    @Override
    public void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(this, message);
    }

    @Override
    public JFrame asFrame() {
        return this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void displayRules(List<String> rules) {
        rulesListModel.clear();

        for (String rule : rules) {
            rulesListModel.addElement(rule);
        }
    }

    @Override
    public void clearResultListModel() {
        resultListModel.clear();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void addElementToResultList(String element) {
        resultListModel.addElement(element);
    }

    @Override
    public String showInputDialog(String question) {
        return JOptionPane.showInputDialog(this, question);
    }

    @Override
    public void enableStartConsultation(boolean enable) {

    }


    private void initComponents() {

        JPanel rulesPanel = MyControls.createJPanel(this, 0, 150, FORM_SIZE.width - 20, FORM_SIZE.height - 250, "Правила");

        rulesListModel = MyControls.CreateJList(rulesPanel, 10, 15, rulesPanel.getWidth() - 20, rulesPanel.getHeight() - 25);


        // shipTable = MyControls.createExpertTable(0, 0, FORM_SIZE.width, 400);
        // shipTable.setVisible(true);

        shipTable = MyControls.getExpertTable(0, 0, FORM_SIZE.width, 400);

        JPanel p = new JPanel();
        p.setSize(FORM_SIZE.width, 400);
        p.setLocation(0, 0);

        // shipTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        p.add(shipTable.getTableHeader(), BorderLayout.NORTH);
        p.add(shipTable, BorderLayout.CENTER);

        shipTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int[] rows = shipTable.getSelectedRows();
                editShipButton.setEnabled(rows.length == 1);
            }
        });

        add(p);

        JButton getRulesJButton = MyControls.createButton("Загрузить правила",
                0, FORM_SIZE.height - 100);

        add(getRulesJButton);
        getRulesJButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getRules();
            }
        });

        editShipButton = MyControls.createButton("Редактировать корабль",
                200, FORM_SIZE.height - 100);
        add(editShipButton);
        editShipButton.setEnabled(false);

        final CallableTask refreshTable = new CallableTask() {
            @Override
            public void execute() {
                List<Ship> ships = Locator.getDatabase().getShips();
                updateShips(ships);
            }
        };

        editShipButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] rows = shipTable.getSelectedRows();
                int index = rows[0];
                Ship ship = Locator.getDatabase().getShips().get(index);

                ShipEditor shipEditor = new ShipEditor(ship, refreshTable);
                shipEditor.setVisible(true);
            }
        });
    }

    private void updateShips(List<Ship> ships) {
        for (int i = 0; i < ships.size(); i++) {
            Ship ship = ships.get(i);
            shipTable.setValueAt(ship.getShipName().getLocalName(), i, 0);
            shipTable.setValueAt(ship.getShipProfile().getName(), i, 1);
            shipTable.setValueAt(ship.getWaterVolume(), i, 2);
            shipTable.setValueAt(ship.getMaxDistance1(), i, 3);
            shipTable.setValueAt(ship.getCfMaxDistance1(), i, 4);
            shipTable.setValueAt(ship.getMaxStaff1(), i, 5);
            shipTable.setValueAt(ship.getCfMaxStaff1(), i, 6);
            shipTable.setValueAt(ship.getMaxDistance2(), i, 7);
            shipTable.setValueAt(ship.getCfMaxDistance2(), i, 8);
            shipTable.setValueAt(ship.getMaxStaff2(), i, 9);
            shipTable.setValueAt(ship.getCfMaxStaff2(), i, 10);
        }
        shipTable.repaint();
    }

    private void initDisposition() {
        setSize(FORM_SIZE);
        setLocationRelativeTo(null);

    }

    private static ExpertFrame instance;

    private void getRules() {
        Controller.get().uploadRules();
    }

    public static ExpertFrame get() {
        if (instance == null) {
            instance = new ExpertFrame();
        }
        return instance;
    }

    private ExpertFrame() {
    }

    private DefaultListModel rulesListModel;
    private DefaultListModel resultListModel;

    private Dimension FORM_SIZE = new Dimension(960, 550);
    private JTextField profileJTextField;
    private JTextField autonomyJTextField;
    private JTextField personalJTextField;
    private JButton consultationJButton;
}
